import { Sequelize } from 'sequelize';
import fs from 'fs';
import path from 'path';

// 读取环境变量配置
const loadEnvConfig = () => {
  try {
    const envPath = path.join(process.cwd(), 'config.env');
    if (fs.existsSync(envPath)) {
      const envContent = fs.readFileSync(envPath, 'utf8');
      const envVars = {};
      
      envContent.split('\n').forEach(line => {
        const [key, value] = line.split('=');
        if (key && value && !key.startsWith('#')) {
          envVars[key.trim()] = value.trim();
        }
      });
      
      return envVars;
    }
  } catch (error) {
    console.log('无法读取配置文件，使用默认配置');
  }
  
  return {};
};

const envConfig = loadEnvConfig();

// 数据库配置
const config = {
  host: envConfig.DB_HOST || process.env.DB_HOST || 'localhost',
  port: envConfig.DB_PORT || process.env.DB_PORT || 5432,
  database: envConfig.DB_NAME || process.env.DB_NAME || 'Family genealogy management',
  username: envConfig.DB_USER || process.env.DB_USER || 'postgres',
  password: envConfig.DB_PASSWORD || process.env.DB_PASSWORD || '10249',
  dialect: 'postgres',
  pool: {
    max: parseInt(envConfig.DB_POOL_MAX) || parseInt(process.env.DB_POOL_MAX) || 20,
    min: parseInt(envConfig.DB_POOL_MIN) || parseInt(process.env.DB_POOL_MIN) || 5,
    acquire: parseInt(envConfig.DB_POOL_ACQUIRE) || parseInt(process.env.DB_POOL_ACQUIRE) || 30000,
    idle: parseInt(envConfig.DB_POOL_IDLE) || parseInt(process.env.DB_POOL_IDLE) || 10000
  },
  logging: process.env.NODE_ENV === 'development' ? console.log : false,
  define: {
    timestamps: true,
    underscored: true,
    freezeTableName: true
  }
};

// 创建Sequelize实例
let sequelize;

try {
  sequelize = new Sequelize(
    config.database,
    config.username,
    config.password,
    {
      host: config.host,
      port: config.port,
      dialect: config.dialect,
      pool: config.pool,
      logging: config.logging,
      define: config.define
    }
  );
  
  console.log('PostgreSQL数据库连接配置成功');
} catch (error) {
  console.error('数据库配置错误:', error);
  throw error;
}

// 测试数据库连接
export const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('✅ PostgreSQL数据库连接成功');
    return true;
  } catch (error) {
    console.error('❌ PostgreSQL数据库连接失败:', error.message);
    return false;
  }
};

// 同步数据库模型
export const syncDatabase = async (force = false) => {
  try {
    await sequelize.sync({ force });
    console.log('✅ 数据库模型同步成功');
    return true;
  } catch (error) {
    console.error('❌ 数据库模型同步失败:', error.message);
    return false;
  }
};

export default sequelize;